import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/common/xindong_button.dart';
import 'package:xindong/widgets/common/xindong_common_dot.dart';
import 'package:xindong/widgets/common/xindong_common_widget.dart';
import 'package:xindong/widgets/common/xindong_text_field.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';

class XinDongReportTypeClass {
  final int id;
  final String value;

  XinDongReportTypeClass({required this.id, required this.value});

  factory XinDongReportTypeClass.fromJson(Map<String, dynamic> json) {
    return XinDongReportTypeClass(id: json['id'], value: json['value']);
  }
}

class XinDongReportYeMian extends StatefulWidget {
  final String userId;

  const XinDongReportYeMian({super.key, required this.userId});

  @override
  State<XinDongReportYeMian> createState() => _XinDongReportYeMianState();
}

class _XinDongReportYeMianState extends State<XinDongReportYeMian> {
  final textEditingController = TextEditingController();
  final phoneController = TextEditingController();
  List<XinDongReportTypeClass> typeList = [];
  int _selectIndex = -1;

  Future<void> _onSubmit() async {
    if (_selectIndex < 0) {
      showToast("请选择要举报的类型");
      return;
    }
    if (textEditingController.text.trim().isEmpty) {
      showToast("举报内容不能为空");
      return;
    }
    if (phoneController.text.trim().isEmpty) {
      showToast("联系方式不能为空");
      return;
    }
    var parameters = {
      "type": 1,
      "report_user": widget.userId,
      "report_selected_id": typeList[_selectIndex].id,
      "desc": textEditingController.text.trim(),
      "phone": phoneController.text.trim(),
    };
    final object = await XinDongNetworking.instance.request(
      XinDongApi.reportUser,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    if (object.code == XinDongServerStatus.success) {
      XinDongAlertMessage.show(
        content: "举报信息已提交，等待平台处理",
        showCancelButton: false,
        hideWhenTouchOutside: false,
        onTapButton: () {
          Get.back();
        },
      );
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final object = await XinDongNetworking.instance.request(XinDongApi.reportList, method: XinDongHttpMethod.post);
      if (object.code == XinDongServerStatus.success) {
        setState(() {
          List list = object.result;
          typeList = list.map((e) => XinDongReportTypeClass.fromJson(e)).toList();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    const padding = EdgeInsets.only(left: kPaddingValue, right: kPaddingValue);
    return Scaffold(
      appBar: XinDongAppBar("匿名举报"),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        child: ListView(
          children: [
            Container(
              height: 40,
              alignment: Alignment.centerLeft,
              padding: padding,
              child: const Text(
                "选择要举报的类型",
                style: TextStyle(fontSize: 14, color: DZColors.titleColor),
              ),
            ),
            ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: typeList.length,
              itemBuilder: (BuildContext context, int index) {
                final model = typeList[index];
                final selected = _selectIndex == index;
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectIndex = index;
                    });
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    height: kCellHeight,
                    color: DZColors.cellColor,
                    padding: padding,
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            model.value,
                            style: const TextStyle(fontSize: 15, color: DZColors.contentColor, height: 1.2),
                          ),
                        ),
                        selected ? const XinDongCommonDot() : const SizedBox(),
                      ],
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return commonDivider();
              },
            ),
            Container(
              height: 40,
              alignment: Alignment.centerLeft,
              padding: padding,
              child: const Text(
                "补充描述",
                style: TextStyle(fontSize: 14, color: DZColors.titleColor),
              ),
            ),
            Container(
              height: 138,
              color: DZColors.cellColor,
              child: TextField(
                keyboardType: TextInputType.multiline,
                maxLines: null,
                // 不限制行数
                style: const TextStyle(color: DZColors.titleColor, fontSize: 15.0, fontWeight: FontWeight.normal),
                controller: textEditingController,
                decoration: const InputDecoration(
                  hintText: "详细说明举报内容吧",
                  hintMaxLines: 2,
                  hintStyle: TextStyle(fontSize: 15, color: DZColors.placeholderColor),
                  contentPadding: EdgeInsets.symmetric(vertical: kPaddingValue, horizontal: kPaddingValue),
                  // 内容偏移上下15，左右16
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                ),
              ),
            ),
            Container(
              height: 40,
              alignment: Alignment.centerLeft,
              padding: padding,
              child: const Text(
                "联系方式",
                style: TextStyle(fontSize: 14, color: DZColors.titleColor),
              ),
            ),
            Container(
              height: kCellHeight,
              color: DZColors.cellColor,
              child: XinDongTextField(
                controller: phoneController,
                contentPadding: padding,
                hintText: "填写你的联系方式，便于我们与你联系",
                keyboardType: TextInputType.emailAddress,
              ),
            ),
            const SizedBox(height: 56),
            Container(
              height: kButtonHeight,
              margin: const EdgeInsets.only(left: 20, right: 20),
              child: XinDongCommonButton("提交", onTap: _onSubmit),
            ),
          ],
        ),
      ),
    );
  }
}
